<script lang="tsx">
import { defineComponent, ref, computed, reactive, onDeactivated } from 'vue';
import { useUserStore } from '@vben/stores';
import { updateUserInfoApi } from '#/api/system/user';
import { ElMessage, ElButton, ElSelect, ElOption, ElTooltip } from 'element-plus';
import { $t } from '@vben/locales';
import { VbenAvatar, VbenIcon } from '@vben-core/shadcn-ui';
import userIcon from '#/assets/images/user-img.png';
import RealnameDialog from './modules/realname-dialog.vue';
import ChangePasswordDialog from './modules/change-password-dialog.vue';
import ChangePhoneDialog from './modules/change-phone-dialog.vue';
import ChangeEmailDialog from './modules/change-email-dialog.vue';
import { RotateCcwKey, IdCard, Pencil } from '@vben/icons';
import { avatarList } from './const';

export default defineComponent({
  name: 'PersonalProfile',
  setup() {
    const userStore = useUserStore();
    const userInfo = computed(() => userStore.userInfo);

    // 实名认证弹窗状态
    const realnameDialogVisible = ref(false);
    // 修改密码弹窗状态
    const changePasswordDialogVisible = ref(false);
    // 修改手机号弹窗状态
    const changePhoneDialogVisible = ref(false);
    // 修改邮箱弹窗状态
    const changeEmailDialogVisible = ref(false);
    // 编辑模式状态
    const isEditing = ref(false);
    // 选中的性别
    const selectedSex = ref('');
    let timeout: number | any;

    // 性别枚举选项
    const sexOptions = [
      { label: '男', value: '1' },
      { label: '女', value: '2' }
    ];

    // 打开实名认证弹窗
    const openRealnameDialog = () => {
      realnameDialogVisible.value = true;
    };

    // 实名认证确认回调
    const handleRealnameConfirm = (data: any) => {
      // 这里可以处理实名认证成功后的逻辑
      console.log('实名认证数据:', data);
      handleRefreshPage();
    };

    // 打开修改密码弹窗
    const openChangePasswordDialog = () => {
      changePasswordDialogVisible.value = true;
    };

    // 修改密码确认回调
    const handlePasswordChangeConfirm = () => {
      // 这里可以处理密码修改成功后的逻辑
      console.log('密码修改成功');
    };

    // 修改密码
    const handleChangePassword = () => {
      openChangePasswordDialog();
    };

    // 打开修改手机号弹窗
    const openChangePhoneDialog = () => {
      changePhoneDialogVisible.value = true;
    };

    // 修改手机号确认回调
    const handlePhoneChangeConfirm = (data: any) => {
      // 这里可以处理手机号修改成功后的逻辑
      console.log('手机号修改数据:', data);
      // 可以刷新用户信息或者更新本地数据
      handleRefreshPage();
    };

    // 修改手机号
    const handleChangePhone = () => {
      openChangePhoneDialog();
    };

    // 打开修改邮箱弹窗
    const openChangeEmailDialog = () => {
      changeEmailDialogVisible.value = true;
    };

    // 修改邮箱确认回调
    const handleEmailChangeConfirm = (data: any) => {
      // 这里可以处理邮箱修改成功后的逻辑
      console.log('邮箱修改数据:', data);
      // 可以刷新用户信息或者更新本地数据
      handleRefreshPage();
    };

    // 修改邮箱
    const handleChangeEmail = () => {
      openChangeEmailDialog();
    };

    // 修改信息
    const handleEditInfo = () => {
      if (isEditing.value) {
        // 保存模式
        handleSaveInfo();
      } else {
        // 编辑模式
        isEditing.value = true;
        selectedSex.value = userInfo.value?.sex || '';
      }
    };

    // 保存信息
    const handleSaveInfo = async () => {
      try {
        await updateUserInfoApi({ sex: selectedSex.value });
        if (userStore.userInfo) {
          userStore.setUserInfo({
            ...userStore.userInfo,
            sex: selectedSex.value
          });
        }
        ElMessage.success($t('common.changeTxt', [$t('common.successTxt')]));
        isEditing.value = false;
      } finally {
      }
    };

    // 取消编辑
    const handleCancelEdit = () => {
      isEditing.value = false;
      selectedSex.value = userInfo.value?.sex || '';
    };

    // 更新头像
    const handleUpdateAvatar = async (avatar: string) => {
      try {
        await updateUserInfoApi({ icon: avatar });
        if (userStore.userInfo) {
          userStore.setUserInfo({
            ...userStore.userInfo,
            icon: avatar
          });
        }
        ElMessage.success($t('personal.avatarUpdateSuccess'));
      } catch (error) {
        throw error;
      }
    };

    // 处理头像更新错误
    const handleAvatarError = (message: string) => {
      ElMessage.error(message);
    };

    // 修改信息成功后刷新页面
    const handleRefreshPage = () => {
      timeout = setTimeout(() => {
        window.location.reload();
      }, 1500)
    };
    onDeactivated(() => {
      timeout && clearInterval(timeout)
    })

    return () => (
      <div class="h-full bg-white rounded-[8px] p-[24px]">
        {/* 顶部区域：头像和按钮 */}
        <div class="flex items-start justify-between mb-[40px]">
          {/* 左侧：头像区域 */}
          <div class="flex items-start gap-[24px]">
            {/* 左侧头像 */}
            <VbenAvatar
              class="w-[128px] h-[128px]"
              src={userInfo.value?.icon || userIcon}
              alt={userInfo.value?.nameCn || $t('common.userTxt')}
              editable={true}
              updateAvatar={handleUpdateAvatar}
              onUpdate={handleUpdateAvatar}
              onError={handleAvatarError}
              avatarList={avatarList}
            />

            {/* 右侧信息区域 */}
            <div class="flex flex-col h-[100px]">
              {/* 上方：姓名和实名认证 */}
              <div class="flex items-center gap-[12px] mt-[42px] mb-[20px]">
                <span class="text-[28px] leading-[32px] text-gray-900">
                  {userInfo.value?.nameCn || '-'}
                </span>
                {userInfo.value?.isRealName ? (
                  <span class="inline-block px-2 py-0.5 text-xs rounded bg-green-100 text-green-700 border border-green-200 mr-2">
                    {$t('personal.realNameVerified')}
                  </span>
                ) : (
                  <span class="inline-block px-2 py-0.5 text-xs rounded bg-[#FA541C33] text-[#C8481D]">
                    {$t('personal.realNameUnverified')}
                  </span>
                )}
              </div>
              {/* 下方：按钮组 */}
              <div>
                {userInfo.value?.isRealName ? '' : (
                  <el-button
                    type="primary"
                    link={true}
                    onClick={openRealnameDialog}
                  >
                    <VbenIcon icon={IdCard} class="w-[14px] h-[14px] mr-[8px]" />
                    {$t('personal.goRealName')}
                  </el-button>
                )}
                <el-button
                  type="primary"
                  link={true}
                  onClick={handleChangePassword}
                >
                  <VbenIcon icon={RotateCcwKey} class="w-[14px] h-[14px] mr-[8px]" />
                  {$t('personal.changePassword')}
                </el-button>
              </div>
            </div>
          </div>

          {/* 右侧：修改信息按钮 */}
          <div class="flex gap-[12px]">
            {isEditing.value && (
              <ElButton
                onClick={handleCancelEdit}
              >
                取消
              </ElButton>
            )}
            <ElButton
              type={isEditing.value ? 'primary' : 'default'}
              onClick={handleEditInfo}
            >
              {isEditing.value ? '保存修改' : '修改信息'}
            </ElButton>
          </div>
        </div>

        {/* 下方：个人信息详情 */}
        <div class="grid grid-cols-3 gap-x-[60px] gap-y-[20px]">
          {/* 姓名 */}
          <div class="flex items-center gap-[12px] h-[32px]">
            <div class="text-[14px] text-[#595959] w-[60px] text-right">姓名</div>
            <div class="text-[14px] text-[#191919]">
              {userInfo.value?.nameCn || '-'}
            </div>
          </div>

          {/* 身份证号 */}
          <div class="flex items-center gap-[12px] h-[32px]">
            <div class="text-[14px] text-[#595959] w-[60px] text-right">身份证号</div>
            <div class="text-[14px] text-[#191919]">
              {userInfo.value?.idCard || '-'}
            </div>
          </div>

          {/* 性别 */}
          <div class="flex items-center gap-[12px] h-[32px]">
            <div class="text-[14px] text-[#595959] w-[60px] text-right">性别</div>
            {isEditing.value ? (
              <ElSelect
                v-model={selectedSex.value}
                placeholder="请选择性别"
                style="width: 120px"
              >
                {sexOptions.map(option => (
                  <ElOption
                    key={option.value}
                    label={option.label}
                    value={option.value}
                  />
                ))}
              </ElSelect>
            ) : (
              <div class="text-[14px] text-gray-900">
                {sexOptions.find(option => option.value === userInfo.value?.sex)?.label || '-'}
              </div>
            )}
          </div>

          {/* 邮箱 */}
          <div class="flex items-center gap-[12px] h-[32px]">
            <div class="text-[14px] text-[#595959] w-[60px] text-right">邮箱</div>
            <div class="text-[14px] text-[#191919] flex items-center gap-[8px] group">
              <span>{userInfo.value?.email || '-'}</span>
              <ElTooltip content={$t('common.editTxt')} placement="top">
                <div
                  class="w-[14px] h-[14px] cursor-pointer"
                  onClick={handleChangeEmail}
                >
                  <VbenIcon
                    icon={Pencil}
                    class="w-[14px] h-[14px] text-gray-400 hover:text-blue-500 transition-colors duration-200"
                  />
                </div>
              </ElTooltip>
            </div>
          </div>

          {/* 手机号 */}
          <div class="flex items-center gap-[12px] h-[32px]">
            <div class="text-[14px] text-[#595959] w-[60px] text-right">手机号</div>
            <div class="text-[14px] text-[#191919] flex items-center gap-[8px] group">
              <span>{userInfo.value?.phone || '-'}</span>
              <ElTooltip content={$t('common.editTxt')} placement="top">
                <div
                  class="w-[14px] h-[14px] cursor-pointer"
                  onClick={handleChangePhone}
                >
                  <VbenIcon
                    icon={Pencil}
                    class="w-[14px] h-[14px] text-gray-400 hover:text-blue-500 transition-colors duration-200"
                  />
                </div>
              </ElTooltip>
            </div>
          </div>
        </div>

        {/* 实名认证弹窗 */}
        <RealnameDialog
          v-model={realnameDialogVisible.value}
          onConfirm={handleRealnameConfirm}
        />

        {/* 修改密码弹窗 */}
        <ChangePasswordDialog
          v-model={changePasswordDialogVisible.value}
          currentPhone={userInfo.value?.phone || ''}
          onConfirm={handlePasswordChangeConfirm}
        />

        {/* 修改手机号弹窗 */}
        <ChangePhoneDialog
          v-model={changePhoneDialogVisible.value}
          currentPhone={userInfo.value?.phone || ''}
          onConfirm={handlePhoneChangeConfirm}
        />

        {/* 修改邮箱弹窗 */}
        <ChangeEmailDialog
          v-model={changeEmailDialogVisible.value}
          currentEmail={userInfo.value?.email || ''}
          onConfirm={handleEmailChangeConfirm}
        />
      </div>
    );
  }
});
</script>
